package com.block.channel.flow.channel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.channel.flow.IChannelReportService;
import com.block.channel.model.result.ReprotFlowResult;
import com.block.channel.service.monitor.VivoMonitorService;
import com.block.common.bean.CommonParam;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.db.entity.ChannelActionMonitorRecord;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.entity.SystemConstantInfo;
import com.block.db.mapper.ChannelActionMonitorRecordMapper;
import com.block.db.mapper.SystemConstantInfoMapper;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class VivoChannelReportService implements IChannelReportService {

    private static Logger log = LogFactory.getCommLog();

//    private String requestUrl = "https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload?nonce={}&advertiserId={}&accessToken={}&timestamp={}";
    private String requestUrl = "https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload?nonce={}&advertiser_id={}&access_token={}&timestamp={}";

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ChannelActionMonitorRecordMapper channelActionMonitorRecordMapper;
    @Resource
    SystemConstantInfoMapper systemConstantInfoMapper;

    @Override
    public ReprotFlowResult registerActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {

        ReprotFlowResult flowResult = new ReprotFlowResult();
        flowResult.setSuccess(false);

        JSONObject headObject = commonParam.getHeadObject();

        String OAID = headObject.getString("originparm1");
        String IMEI_MD5 = headObject.getString("originparm2");

        if (StrUtil.isEmpty(OAID)) {
            flowResult.setCode("-2");
            flowResult.setMessage("OAID和IMEI_MD5参数为空，不做处理");
            return flowResult;
        }

        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            flowResult.setCode("-2");
            flowResult.setMessage("获取token为空");
            return flowResult;
        }

        //
//        ChannelActionMonitorRecord monitorRecord = channelActionMonitorRecordMapper.queryEntityByUnikeyAndActionType(OAID, "CLICK", channelBaseInfo.getChannelCode());
//        if (ObjectUtil.isEmpty(monitorRecord)) {
//            flowResult.setCode("-2");
//            flowResult.setMessage("可上报信息为空");
//            return flowResult;
//        }

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("srcType", "APP");
        bizMap.put("pkgName", "com.hzlz.zxfq");
        bizMap.put("srcId", "ds-202407179352");// todo

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userIdType", "OAID");
//        jsonObject.put("userId", monitorRecord.getUniqueKey());
        jsonObject.put("userId", OAID);
        jsonObject.put("cvType", "REGISTER");

//        String callbackInfo = monitorRecord.getCallbackInfo();
//        if (StrUtil.isNotEmpty(callbackInfo)){
//            JSONObject extData = JSON.parseObject(callbackInfo);
//            jsonObject.putAll(extData);
//        }

//        jsonObject.put("requestId", monitorRecord.getCallbackInfo());

//        long actionTime = LocalDateTime.now().toInstant(ZoneOffset.of(getZoneStr(TIME_ZONE))).toEpochMilli();
//        Long actionTime = LocalDateUtil.getTimeMillis(monitorRecord.getCreateTime());
//        Long actionTime = LocalDateUtil.getTimeMillis(monitorRecord.getCreateTime());
        Long actionTime = System.currentTimeMillis();
        jsonObject.put("cvTime", actionTime);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject);

        // 需要查询表信息
        bizMap.put("dataList", jsonArray);

        String timestamp = System.currentTimeMillis()+"";// todo
        String advertiserId = "33b753773a30c7066b2b";// todo
        String nonce = UUID.randomUUID().toString().replaceAll("-","");
        String reqUrl = StrUtil.format(requestUrl, nonce, advertiserId, token, timestamp);

        log.info("【VIVO信息流上报】【注册】【开始请求】【reqestUrl】{}【bizMap】{}", reqUrl, JSON.toJSONString(bizMap));
        String response = HttpUtil.createPost(reqUrl)
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【VIVO信息流上报】【注册】【开始结束】【result】{}", response);

        JSONObject resultObject = JSONObject.parseObject(response);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        flowResult.setCode(String.valueOf(code));
        flowResult.setMessage(message);
        flowResult.setParamInfo(JSON.toJSONString(bizMap));
        flowResult.setResultInfo(response);
        if (ObjectUtil.equals(code, Integer.valueOf(0))){
            flowResult.setSuccess(true);
        }else{
            flowResult.setSuccess(false);
        }

        return flowResult;
    }
    @Override
    public ReprotFlowResult sourceActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }
    @Override
    public ReprotFlowResult downloadActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

    @Override
    public ReprotFlowResult payBuyActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

    public String getToken() {
        String redisKey = StrUtil.format(RedisKeyConstant.VIVO_CHANNEL_ACCESS_TOKEN, VivoMonitorService.CLIENT_ID);
        String token = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }

        // 为空，或者超时，则触发刷新操作
        SystemConstantInfo tokenInfo = systemConstantInfoMapper.getEntityByCode(VivoMonitorService.CODE_VIVO_TOKEN);
        if (ObjectUtil.isNotEmpty(tokenInfo)){
            // 更新access token 缓存信息
            stringRedisTemplate.opsForValue().set(redisKey, tokenInfo.getContentInfo(), 7, TimeUnit.DAYS);
            return tokenInfo.getContentInfo();
        }
        return null;

    }


}
